package com.example.oa;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBCPDatasource {
    private static final BasicDataSource BASIC_DATA_SOURCE = new BasicDataSource();
    static {

//        BASIC_DATA_SOURCE.setUrl("jdbc:mysql://127.0.0.1:3306?serverTimezone=UTC");
        BASIC_DATA_SOURCE.setUrl("jdbc:mysql:///?serverTimezone=UTC");
        BASIC_DATA_SOURCE.setUsername("root");
        BASIC_DATA_SOURCE.setPassword("root");
        BASIC_DATA_SOURCE.setDriverClassName("com.mysql.cj.jdbc.Driver");
    }

    public static Connection getConnection(){
        try {
            return BASIC_DATA_SOURCE.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将连接交回给DBCP连接池，由连接池管理该连接
     * @param connection 数据库连接池的连接
     * @param preparedStatement 用户自定义preparedStatement 对象
     * @param resultSet 用户自定义resultSet 对象
     */
    public static void closeSqlConnect(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (preparedStatement != null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
